using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class MouseInputUtils
{
    public static T GetFirstComponent<T>() where T : Component{
        Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D[] hit = Physics2D.RaycastAll(mousePosition,Vector3.forward);

        for (int i = 0; i < hit.Length; ++i) {
            if (hit[i] != null && hit[i].collider != null) {
                T component = hit[i].collider.GetComponent<T>();
                return component;
            }   
        }

        return null;
    }

    public static T GetFirstComponentFromUI<T>() where T : Component {
        Vector3 mousePosition = Input.mousePosition;
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.position = mousePosition;

        List<RaycastResult> results = new();
        EventSystem.current.RaycastAll(eventData,results);
        for (int i = 0; i < results.Count; ++i) {
            T component = results[i].gameObject.GetComponent<T>();
            if (component != null) {
                return component;
            }
        }

        return null;
    }
}
